package com.jwdf.uda.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.ExtraBaseQuestion;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.FragmentQuizDetailBinding;
import com.jwdf.uda.event.MessageNoticeEvent;
import com.jwdf.uda.event.NewProblemsEvent;
import com.jwdf.uda.event.QuizDetailEvent;
import com.jwdf.uda.event.ReplyDetailEvent;
import com.jwdf.uda.event.TitleEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.UserReadMessageAction;
import com.jwdf.uda.ui.activity.presenter.QuizDetailPresenter;
import com.jwdf.uda.ui.activity.view.IQuizDetailView;
import com.jwdf.uda.ui.adapter.QuizDetailAdapter;
import com.jwdf.uda.ui.adapter.item.QuizDetailItem;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.view.FilterMenu;
import com.jwdf.uda.view.XListView;
import com.jwdf.uda.view.dialog.ConfirmDialog;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/5.
 */
public class QuizDetailActivity extends AbsTitleBarActivity {
    private final static String EXTRA_QUIZ_ID = "id";
    private final static String EXTRA_MSG_ID = "msg_id";
    private final static String EXTRA_IS_AUTHOR = "is_author";

    private FilterMenu mFilterMenu;

    public static void start(Context context, int id) {
        start(context, id, false);
    }

    public static void start(Context context, int id, boolean isAuthor) {
        Intent intent = new Intent(context, QuizDetailActivity.class);
        intent.putExtra(EXTRA_QUIZ_ID, id);
        intent.putExtra(EXTRA_IS_AUTHOR, isAuthor);
        context.startActivity(intent);
    }

    public static void start(Context context, int id, int msgId) {
        Intent intent = new Intent(context, QuizDetailActivity.class);
        intent.putExtra(EXTRA_QUIZ_ID, id);
        intent.putExtra(EXTRA_MSG_ID, msgId);
        context.startActivity(intent);
    }

    @Override
    protected String getTopTitle() {
        return getString(R.string.title_quiz_detail);
    }

    @Override
    protected BaseFragment onCreateContentFragment() {
        return new QuizDetailFragment();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        boolean isAuthor = getIntent().getBooleanExtra(EXTRA_IS_AUTHOR, false);
        int messageId = getIntent().getIntExtra(EXTRA_MSG_ID, 0);
        mFilterMenu = createFilterMenu(this);
        List<String> items = new ArrayList<>();
        if (isAuthor) {
            items.add(getString(R.string.quiz_delete));
            items.add(getString(R.string.quiz_edit));
            items.add(getString(R.string.quiz_detail_share));
        } else {
            items.add(getString(R.string.quiz_detail_share));
            items.add(getString(R.string.do_report));
        }
        mFilterMenu.bindMenuData(items);
        mFilterMenu.setOnMenuItemSelectedListener(createMenuItemListener());
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
        if (messageId != 0) {
            onNewRequestCall(UserReadMessageAction.newInstance(this, messageId).request(new AHttpService.IResCallback<PbBean.PbResUserReadMessage>() {
                @Override
                public void onCallback(int resultCode, Response<PbBean.PbResUserReadMessage> response, PbBean.PbBaseServerInfo baseServerInfo) {
                    if (HttpHelper.showError(QuizDetailActivity.this, resultCode, baseServerInfo, R.string.error_net)) {
                        return;
                    }
                    EventBusUtil.post(new MessageNoticeEvent(MessageNoticeEvent.HAS_READ_MESSAGE));
                }
            }));
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        ((QuizDetailFragment) mFragment).registerEvent();
    }

    @Override
    protected void onStop() {
        ((QuizDetailFragment) mFragment).unregisterEvent();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        EventBusUtil.unregisterEvent(this);
        super.onDestroy();
    }

    public void onEventMainThread(TitleEvent event) {
        if (TitleEvent.EVENT_QUIZ_TITLE == event.getEventType()) setTopTitle(event.getTitle());
    }

    @Override
    protected void setupTitleView() {
        setOperateTitleIconAction(R.mipmap.ic_detail_menu_more);
    }

    @Override
    protected Bundle onPutArguments() {
        Bundle args = new Bundle();
        args.putInt(EXTRA_QUIZ_ID, getIntent().getIntExtra(EXTRA_QUIZ_ID, 0));
        return args;
    }

    @Override
    public void onHeadActionClick(View view) {
        if (((QuizDetailFragment) mFragment).titleMenuEnabled()) {
            mFilterMenu.show(view);
        }
    }

    private FilterMenu.MenuItemAdapter.OnMenuItemSelectedListener createMenuItemListener() {
        return new FilterMenu.MenuItemAdapter.OnMenuItemSelectedListener() {
            @Override
            public void onMenuItemSelected(String item, int position) {
                mFilterMenu.dismissFilterMenu();
                if (TextUtils.equals(item, getString(R.string.quiz_delete))) {
                    ((QuizDetailFragment) mFragment).showDelQuizConfirmDialog();
                } else if (TextUtils.equals(item, getString(R.string.quiz_edit))) {
                    ((QuizDetailFragment) mFragment).onQuizEdit();
                } else if (TextUtils.equals(item, getString(R.string.quiz_detail_share))) {
                    ((QuizDetailFragment) mFragment).onQuizShare();
                } else if (TextUtils.equals(item, getString(R.string.do_report))) {
                    ((QuizDetailFragment) mFragment).onQuizReport();
                }
            }
        };
    }

    private FilterMenu createFilterMenu(Context context) {
        FilterMenu menu = new FilterMenu(context, R.drawable.filter_menu_bg);
        return menu;
    }

    public static class QuizDetailFragment extends BaseFragment implements IQuizDetailView {

        private PbBean.PbSignBaseAnswerSort mSort;
        private FragmentQuizDetailBinding mBinding;
        private QuizDetailPresenter mPresenter;
        private QuizDetailAdapter mAdapter;
        private ConfirmDialog mDelDataDialog;
        private ConfirmDialog mVoteCfmDialog;
        private ConfirmDialog mReVoteCfmDialog;
        private FilterMenu mSortMenu;
        private String mQuizTitle;
        private int mQuizId;
        private XListView.IXListViewListener mIXListener = new XListView.IXListViewListener() {
            @Override
            public void onRefresh(XListView xListView) {
                mPresenter.requestDetail();
            }

            @Override
            public void onLoadMore(XListView xListView) {
                if (mAdapter.getCurrentTab() == QuizDetailItem.QuizTab.REPLY) {
                    mPresenter.getReplyListAction(mAdapter.getCommentOffset(), mSort);
                } else if (mAdapter.getCurrentTab() == QuizDetailItem.QuizTab.VOTE) {
                    mPresenter.getVoteListAction(mAdapter.getVoteOffset());
                }
            }
        };

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_quiz_detail, container, false);
            initViews();
            return mBinding.getRoot();
        }

        private void initViews() {
            mQuizId = getArguments().getInt(EXTRA_QUIZ_ID);
            mAdapter = new QuizDetailAdapter(getActivity());
            mBinding.lvData.setPullRefreshEnable(false);
            mBinding.lvData.setXListViewListener(mIXListener);
            mBinding.lvData.setOnScrollListener(createOnScrollListener());
            mBinding.lvData.addHeaderView(createHeaderView());
            mBinding.lvData.setAdapter(mAdapter);
            mPresenter = new QuizDetailPresenter(this, mQuizId);
            mPresenter.requestDetail();
            EventBusUtil.registerEvent(this);
        }

        @Override
        public void onDestroyView() {
            EventBusUtil.unregisterEvent(this);
            super.onDestroyView();
        }

        public void registerEvent() {
            EventBusUtil.registerEvent(mPresenter);
            EventBusUtil.registerEvent(mAdapter);
        }

        public void unregisterEvent() {
            EventBusUtil.unregisterEvent(mAdapter);
            EventBusUtil.unregisterEvent(mPresenter);
        }

        private AbsListView.OnScrollListener createOnScrollListener() {
            return new XListView.OnXScrollListener() {
                @Override
                public void onXScrolling(View view) {

                }

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    int viewType = view.getAdapter().getItemViewType(view.getFirstVisiblePosition());
                    mBinding.floatingTab.getRoot().setVisibility(QuizDetailItem.TYPE_TITLE_TAB <= viewType ? View.VISIBLE : View.GONE);
                    EventBusUtil.post(new TitleEvent(TitleEvent.EVENT_QUIZ_TITLE, viewType > QuizDetailItem.TYPE_QUIZ_MAIN ? getQuizTitle() : getString(R.string.title_quiz_detail)));
                }
            };
        }

        private View createHeaderView() {
            View headerView = getActivity().getLayoutInflater().inflate(R.layout.view_head_divider, null);
            return headerView;
        }

        @Override
        public int getPageLength() {
            return super.getPageLength();
        }

        @Override
        public BaseFragment getFragment() {
            return this;
        }

        @Override
        public void onHeadActionClick() {
        }

        @Override
        public void setPullLoadEnable(boolean enable) {
            mBinding.lvData.setPullRefreshEnable(true);
            mBinding.lvData.setPullLoadEnable(enable);
            mBinding.lvData.stopRefresh();
            mBinding.lvData.stopLoadMore();
        }

        @Override
        public QuizDetailItem.QuizTab getCurrentTab() {
            return mAdapter.getCurrentTab();
        }

        @Override
        public void setCurrentTab(QuizDetailItem.QuizTab tab) {
            mAdapter.setCurrentTab(tab);
            if (tab == QuizDetailItem.QuizTab.VOTE) {
                showTabVote();
            } else {
                showTabComment();
            }
        }

        public void onEventMainThread(NewProblemsEvent event) {
            if (NewProblemsEvent.EVENT_COMMENT_SUBMIT == event.getEvent()) {
                mPresenter.requestDetail();
            }
        }

        public void onEventMainThread(ReplyDetailEvent event) {
            if (event != null && ReplyDetailEvent.EVENT_COMMENT_ADD == event.getEvent()) {
                mPresenter.requestDetail();
            }
        }

        public void onEventMainThread(QuizDetailEvent event) {
            switch (event.getEvent()) {
                case QuizDetailEvent.EVENT_DO_SORT:
                    mBinding.floatingTab.tvSort.setText(event.getSortType());
                    break;
                case QuizDetailEvent.EVENT_QUIZ_REPLY_ADD:
                case QuizDetailEvent.EVENT_QUIZ_REPLY_DEL:
                case QuizDetailEvent.EVENT_QUIZ_REPLY_EDIT:
                    mPresenter.requestDetail();
                    break;
            }
        }

        @Override
        public void showBottomView(final int answerId, final int voteCount) {
            final boolean isAnswered = answerId > 0;
            mBinding.itemDetailBottom.tvEditReply.setVisibility(isAnswered ? View.VISIBLE : View.GONE);
            mBinding.itemDetailBottom.tvAddReply.setVisibility(isAnswered ? View.GONE : View.VISIBLE);
            mBinding.itemDetailBottom.getRoot().setVisibility(View.VISIBLE);
            mBinding.itemDetailBottom.btnReply.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!isAnswered) {
                        mPresenter.toAddReplyActivity(getActivity(), voteCount);
                    } else {
                        //                        mPresenter.userEditReply(answerId,voteCount);
                        ReplyDetaiActivtiy.start(v.getContext(), answerId, true, voteCount, new ExtraBaseQuestion());
                    }
                }
            });
            mBinding.itemDetailBottom.btnAddInvite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SearchInvitationActivity.start(getContext(), mQuizId);
                }
            });
        }

        @Override
        public void showTabSortMenu(View anchor) {
            if (mSortMenu == null) {
                mSortMenu = new FilterMenu(getContext(), R.mipmap.bg_filter_sort);
                List<String> items = new ArrayList<>();
                items.add(getString(R.string.zan_sort));
                items.add(getString(R.string.time_sort));
                mSortMenu.bindMenuData(items);
                mSortMenu.setOnMenuItemSelectedListener(createMenuItemListener());
            }
            mSortMenu.show(anchor);
        }

        private FilterMenu.MenuItemAdapter.OnMenuItemSelectedListener createMenuItemListener() {
            return new FilterMenu.MenuItemAdapter.OnMenuItemSelectedListener() {
                @Override
                public void onMenuItemSelected(String item, int position) {
                    mSortMenu.dismissFilterMenu();
                    mSort = 0 == position ? PbBean.PbSignBaseAnswerSort.ANSWER_SORT_BY_LIKE_DESC : PbBean.PbSignBaseAnswerSort.ANSWER_SORT_BY_TIME_DESC;
                    mPresenter.getReplyListAction(0, mSort);
                }
            };
        }

        @Override
        public boolean titleMenuEnabled() {
            return View.VISIBLE == mBinding.flBottom.getVisibility();
        }

        @Override
        public void showDetailData(PbBean.PbResQuestionFindQuestion body) {
            mAdapter.setDetailData(body);
            mQuizTitle = body.getQuestionInfo().getTitle();
            setTitleTabData(mAdapter.getTitleTabItem(body));
        }

        private void showTabVote() {
            mBinding.floatingTab.tvSort.setSelected(false);
            mBinding.floatingTab.tvTabComment.setSelected(false);
            mBinding.floatingTab.tvTabVote.setSelected(true);
            mBinding.floatingTab.tvVoteTitleComment.setSelected(false);
            mBinding.floatingTab.tvVoteTitleText.setSelected(true);
            mBinding.floatingTab.vLineComment.setVisibility(View.GONE);
            mBinding.floatingTab.vLineVote.setVisibility(View.VISIBLE);
            mBinding.floatingTab.flDropMenu.setVisibility(View.GONE);
            mBinding.floatingTab.divider.setVisibility(View.GONE);
        }

        private void showTabComment() {
            mBinding.floatingTab.tvSort.setSelected(true);
            mBinding.floatingTab.tvTabComment.setSelected(true);
            mBinding.floatingTab.tvTabVote.setSelected(false);
            mBinding.floatingTab.tvVoteTitleComment.setSelected(true);
            mBinding.floatingTab.tvVoteTitleText.setSelected(false);
            mBinding.floatingTab.vLineComment.setVisibility(View.VISIBLE);
            mBinding.floatingTab.vLineVote.setVisibility(View.GONE);

            mBinding.floatingTab.flDropMenu.setVisibility(mPresenter.mDetail.getQuestionInfo().getAnswerCount() > 0 ? View.VISIBLE : View.GONE);
            mBinding.floatingTab.divider.setVisibility(mPresenter.mDetail.getQuestionInfo().getAnswerCount() > 0 ? View.VISIBLE : View.GONE);
        }

        @Override
        public void setTitleTabData(final QuizDetailItem item) {
            mBinding.floatingTab.tvTabComment.setText(String.valueOf(item.replyCount));
            mBinding.floatingTab.tvTabVote.setText(String.valueOf(item.voteCount));
            mBinding.floatingTab.tvSort.setText(item.sortType);
            mBinding.floatingTab.flTabVote.setVisibility(item.hasVoteOption ? View.VISIBLE : View.GONE);

            if (item.currentTab == QuizDetailItem.QuizTab.VOTE) {
                showTabVote();
            } else {
                showTabComment();
            }

            mBinding.floatingTab.flTabComment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    QuizDetailEvent event = new QuizDetailEvent(QuizDetailEvent.EVENT_TAB_REPLY);
                    event.count = item.replyCount;
                    EventBusUtil.post(event);
                }
            });
            mBinding.floatingTab.flTabVote.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    QuizDetailEvent event = new QuizDetailEvent(QuizDetailEvent.EVENT_TAB_VOTE);
                    event.count = item.voteCount;
                    EventBusUtil.post(event);
                }
            });
            mBinding.floatingTab.flDropMenu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.replyCount > 0) {
                        item.currentTab = QuizDetailItem.QuizTab.REPLY;
                        QuizDetailEvent event = new QuizDetailEvent(QuizDetailEvent.EVENT_SHOW_DROP_MENU);
                        event.anchor = v;
                        EventBusUtil.post(event);
                    }
                }
            });
        }

        @Override
        public String getQuizTitle() {
            return mQuizTitle;
        }

        @Override
        public int getAdapterCount() {
            return mAdapter.getCount();
        }

        @Override
        public void onQuizShare() {
            mPresenter.doShareAction(getContext());
        }

        @Override
        public void onQuizEdit() {
            EditProblemsActivity.start(getContext(), mPresenter.mDetail);
        }

        @Override
        public void onQuizReport() {
            FeedbackActivity.start(getActivity(), mQuizId, true);
        }

        @Override
        public void showDelQuizConfirmDialog() {
            if (mDelDataDialog == null) {
                mDelDataDialog = new ConfirmDialog(getActivity(), getString(R.string.dialog_del_quiz), getString(R.string.dialog_del_cancel), getString(R.string.dialog_del_sure));
                mDelDataDialog.setCallbackListener(new ConfirmDialog.CallbackListener() {
                    @Override
                    public void clickNo() {

                    }

                    @Override
                    public void clickYes() {
                        mPresenter.doDelQuizAction();
                    }
                });
            }
            mDelDataDialog.show();
        }

        @Override
        public void showVoteConfirmDialog(final PbBean.PbSignBaseVoteOptionType optionId) {
            if (mVoteCfmDialog == null) {
                mVoteCfmDialog = new ConfirmDialog(getActivity(), getString(R.string.dialog_set_vote), getString(R.string.dialog_del_cancel), getString(R.string.do_vote_sure_btn));
            }
            mVoteCfmDialog.setCallbackListener(new ConfirmDialog.CallbackListener() {
                @Override
                public void clickNo() {
                    QuizDetailEvent event = new QuizDetailEvent(QuizDetailEvent.EVENT_VOTE_CANCELED);
                    event.optionId = optionId;
                    EventBusUtil.post(event);
                }

                @Override
                public void clickYes() {
                    mPresenter.doVoteAction(optionId);
                }
            });
            mVoteCfmDialog.show();
        }

        @Override
        public void showReVoteConfirmDialog(final PbBean.PbSignBaseVoteOptionType optionId) {
            if (mReVoteCfmDialog == null) {
                mReVoteCfmDialog = new ConfirmDialog(getActivity(), getString(R.string.dialog_set_vote), getString(R.string.dialog_del_cancel), getString(R.string.do_vote_sure_btn));
            }
            mReVoteCfmDialog.setCallbackListener(new ConfirmDialog.CallbackListener() {
                @Override
                public void clickNo() {
                }

                @Override
                public void clickYes() {
                    mPresenter.doVoteAction(optionId);
                }
            });
            mReVoteCfmDialog.show();
        }

        @Override
        public void refreshComments(List<PbBean.PbBaseQuestionAnswer> comments, int commentCount) {
            mAdapter.refreshCommentCount(commentCount);
            mAdapter.refreshComments(comments);
        }

        @Override
        public void loadMoreComments(List<PbBean.PbBaseQuestionAnswer> comments) {
            mAdapter.loadMoreComments(comments);
        }

        @Override
        public void refreshVotes(PbBean.PbResQuestionVoteInfo voteList) {
            mAdapter.refreshVoteCount(voteList.getVoteCount());
            mAdapter.refreshVotes(voteList);
        }

        @Override
        public void loadMoreVotes(List<PbBean.PbBaseVoterInfo> voters) {
            mAdapter.loadMoreVotes(voters);
        }

        @Override
        public void showUserTakeVote(int voteOptionCount) {
            mAdapter.showUserTakeVote(voteOptionCount);
        }

        @Override
        public int getCommentOffset() {
            return mAdapter.getCommentOffset();
        }

        @Override
        public int getVoteOffset() {
            return mAdapter.getVoteOffset();
        }
    }

}
